// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
		player:{
			default:null,
			type:cc.Sprite
		},
		dialog:{
			default:null,
			type:cc.Node
		},
		checkButton:{
			default:null,
			type:cc.Button
		},
		eventsContent:{
			default:null,
			type:cc.Label
		}
    },

	tryMoveToNewTile: function(newTile) {
        var mapSize = this.tiledMap.getMapSize();
        if (newTile.x < 0 || newTile.x >= mapSize.width) return;
        if (newTile.y < 0 || newTile.y >= mapSize.height) return;

        if (this.roads.getTileGIDAt(newTile)) {
            this.playerTile = newTile;
			this.updatePlayerPos();
        }
        if (this.events.getTileGIDAt(this.playerTile)) {
            // 显示按钮
			this.checkButton.node.active = true;
		}else{
			// 隐藏按钮
			this.checkButton.node.active = false;
		}
        
    },
	checkEvent:function(){
		var p =this.eventsX[this.playerTile.x][this.playerTile.y];
		
	
		var script = this.dialog.getComponent("dialog");
		script.resetTC(this.eventsContent[p][0]);
		if (!(this.eventsContent[p][1]==undefined)){
			var ep = this.eventsContent[p][1].split("，");
			for (var i = 0;i<ep.length;i++){
				this.eventsContent[Math.floor(ep[i])] = this.eventsContent[ep[i]];
			}
		}
		if (!(this.eventsContent[p][2]==undefined)){
			
			var command = this.eventsContent[p][2].split(' ');
			
			if (command[0]=='jp'){
				this.dialog.finishCallBack=function(){
					cc.director.loadScene(command[1]);
				}
			}
		}
	},
    onLoad () {
		
		var script = this.dialog.getComponent("dialog");
		this.node.on(cc.Node.EventType.TOUCH_END,script.nextTc,script);
		
		this.tiledMap = this.node.getComponent(cc.TiledMap);
        this.roads = this.tiledMap.getLayer('可通过');
        this.events = this.tiledMap.getLayer('事件方块');
		this.playerTile = this.getTilePos(this.player.node.getPosition());
        var self = this;
		this.player_sc = this.player.getComponent('Player');
		cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,function(keyCode, event) {
                var newTile = cc.p(self.playerTile.x, self.playerTile.y);
                switch(keyCode.keyCode) {
                    case cc.KEY.up:
                        newTile.y -= 1;
						this.player.node.switchPhoto(1);
                        break;
                    case cc.KEY.down:
                        newTile.y += 1;
						this.player.node.switchPhoto(0);
                        break;
                    case cc.KEY.left:
                        newTile.x -= 1;
						this.player.node.switchPhoto(2);
                        break;
                    case cc.KEY.right:
                        newTile.x += 1;
						this.player.node.switchPhoto(3);
                        break;
                    default:
                        return;
                }

                self.tryMoveToNewTile(newTile);

            }
        ,self);
		var script = this.dialog.getComponent("dialog");
		this.node.on(cc.Node.EventType.TOUCH_END,script.nextTc,script);
		var	self = this;
		this.dialog.finishCallBack=function(){
			self.dialog.active = false;
		}
		var mapSize = this.tiledMap.getMapSize();
		// 初始化事件块映射
		var c = 1
		this.eventsX = []
		for (var x =0;x <mapSize.width;x++){
			this.eventsX[x] = [];
		}
		for (var y= 0;y<mapSize.height;y++){
			for (var x =0;x <mapSize.width;x++){
				var v = cc.v2(x,y);
				if (this.events.getTileGIDAt(v)){
					this.eventsX[x][y] = c;
					c ++;
				}
			}
		}
		// 事件方块台词
		var eventsContent = this.eventsContent.string.split('\n');
		this.eventsContent = {}
		for (var i =0;i<eventsContent.length;i++){
			var t = eventsContent[i].split('：');
			t[1] = "0："+t[1];
			var events = t[0].split('@');
			var ep = events[0].split('！');
			var kp = ep[0].split('，');
			for (var k=0;k<kp.length;k++){
				this.eventsContent[kp[k]]=[t[1],ep[1],events[1]];	
			}
		}
	},

    start () {
		
    },
	getTilePos: function(posInPixel) {
        var mapSize = this.node.getContentSize();
        this.tileSize = this.tiledMap.getTileSize();
        var x = Math.floor(posInPixel.x / this.tileSize.width);
        var y = Math.floor((mapSize.height - posInPixel.y) / this.tileSize.height);
        return cc.p(x, y);
    },


    updatePlayerPos: function() {
        var pos = this.roads.getPositionAt(this.playerTile);
		pos.x += this.tileSize.width/2;
		pos.y += this.tileSize.height/2;
		
        this.player.node.setPosition(pos);
    },
    // update (dt) {},
});
